package band.wukong.practice.java.core.topic.concurrency.threadpool;

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author wukong(wukonggg@139.com)
 */
public class ExecutorSample {

    public static void main(String[] args) {
        newFixedThreadPool();
        newSingleThreadExecutor();
        newScheduledThreadPool();
    }

    /**
     * 创建固定数目线程的线程池。
     */
    private static void newFixedThreadPool() {
        Runnable task = () -> System.out.println(Thread.currentThread().getName() + ": 把握时代脉搏！");
        Runnable task2 = () -> System.out.println(Thread.currentThread().getName() + ": 把握时代脉搏！！！");

        Executor executor = Executors.newFixedThreadPool(2);
        executor.execute(task);
        executor.execute(task);
        executor.execute(task2);

    }

    /**
     * 创建一个单线程化的Executor。
     */
    private static void newSingleThreadExecutor() {
        Runnable task = () -> System.out.println(Thread.currentThread().getName() + ": 永远跟着党走！");
        Runnable task2 = () -> System.out.println(Thread.currentThread().getName() + ": 永远跟着党走！！！");

        Executor executor = Executors.newSingleThreadExecutor();
        executor.execute(task);
        executor.execute(task);
        executor.execute(task2);
    }

    /**
     * 创建一个支持定时及周期性的任务执行的线程池，多数情况下可用来替代Timer类。
     */
    private static void newScheduledThreadPool() {
        Runnable task = () -> System.out.println(Thread.currentThread().getName() + ": 雄安新区万岁！");
        Runnable task2 = () -> System.out.println(Thread.currentThread().getName() + ": 雄安新区万岁！！！");

        Executor executor = Executors.newScheduledThreadPool(2);
        ScheduledExecutorService scheduler = (ScheduledExecutorService) executor;
        scheduler.scheduleAtFixedRate(task, 5, 3, TimeUnit.SECONDS);
        scheduler.scheduleAtFixedRate(task, 5, 3, TimeUnit.SECONDS);
        scheduler.scheduleAtFixedRate(task2, 5, 3, TimeUnit.SECONDS);
    }
}
